import { HsAdminDelete, HsAdminInput, HsAdminPage, HsAdminSelect, HsAdminSpin } from '@hs-admin/base-components'
import { Button, Flex, Form, Row, Col } from 'antd'
import { message, usePage } from '@hs-admin/utils'
import { FC, memo, useEffect, useRef, useState } from 'react'
import {
  getDataItemSettingList,
  addDataItemSetting,
  editDataItemSetting,
  deleteDataItemSetting,
  getDataItemPolymerizeOptions
} from '@/api/setting/item'
import { dataItemSettingType } from '@/utils/type'
import { useSearchParams } from 'react-router-dom'
import PolymerizeOptions from './PolymerizeOptions'
import { ServerCoreField } from '@hs-server/components'
import { reqDataItemColumns } from '@hs-admin/api'
import { useImmer } from 'use-immer'
import _ from 'lodash'

interface Props {}
const Filtrate: FC<Props> = () => {
  const [searchParams] = useSearchParams()
  const id: string | null = searchParams?.get('id')
  const [form] = Form.useForm()
  const [typeOptions, setTypeOptions] = useState(dataItemSettingType())
  const [loading, setloading] = useState(true)
  const polymerizeOptionsRef = useRef<any>({})
  const allColumnList = useRef<any[]>([])
  const [typeInfor, settypeInfor] = useImmer<any>({
    columnList: [],
    tableList: []
  })

  const callList = () => {
    setloading(true)
    return getDataItemSettingList({ release_item_id: id, page: pagination.current, page_size: pagination.pageSize })
      .then((res) => {
        const list = res.items.map((item: any) => ({
          ...item,
          ...item.config,
          config: {
            ...item.config,
            old_province_column: item.config.province_column,
            old_city_column: item.config.city_column,
            old_area_column: item.config.area_column,
            old_column: item.config.column
          },
          checkList: item.config.options ?? [],
          updateType: 'edit',
          disabled:
            // 园区筛选
            (item.type === 'park' && item.config.column === 'carrier_list') ||
            // 产业筛选
            (item.type === 'industry' && item.config.column === 'hs_ind_list') ||
            // 国民经济分类筛选
            (item.type === 'national_economy_classification' && item.config.column === 'nea_ind_list') ||
            // 战新产业筛选
            (item.type === 'strategic_industry' && item.config.column === 'strategic_ind_list') ||
            // 资质筛选
            (item.type === 'qualification' && item.config.column === 'qualified_list')
        }))
        form.setFieldValue('settingList', list)
        settypeInfor((prev: { tableList: any }) => {
          prev.tableList = _.cloneDeep(list)
        })
        setTotal(res.total)
        list.forEach((item: { type: string; column: any; polymerizeOptionsLength: any }) => {
          if (item.type === 'polymerize') {
            setloading(true)
            getDataItemPolymerizeOptions({ release_item_id: id, column_name: item.column })
              .then((res) => {
                item.polymerizeOptionsLength = res.length
                form.setFieldValue('settingList', [...list])
              })
              .finally(() => {
                setloading(false)
              })
          }
        })
      })
      .finally(() => {
        setloading(false)
      })
  }
  const { pagination, setTotal }: { pagination: UsePageProps; setTotal: (total: number) => number } = usePage(callList)

  // 筛选项类型
  const typeChange = (key: number, value: string) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    item.type = value
    item.release_item_id = id
    Reflect.deleteProperty(item.config, 'value')
    const handleImmobilizationColumn = () => {
      item.disabled = true
      const findItem: any = allColumnList.current.find((ele: any) => ele.name === item.config.column)
      item.name = findItem?.comment
      form.setFieldValue('settingList', settingList)
      handleChange(settingList, key, item)
    }
    // 园区
    if (item.type === 'park') {
      item.column = 'carrier_list'
      item.config.column = 'carrier_list'
      handleImmobilizationColumn()
      return
    }
    // 产业
    if (item.type === 'industry') {
      item.column = 'hs_ind_list'
      item.config.column = 'hs_ind_list'
      handleImmobilizationColumn()
      return
    }
    // 国民经济分类筛选
    if (item.type === 'national_economy_classification') {
      item.column = 'nea_ind_list'
      item.config.column = 'nea_ind_list'
      handleImmobilizationColumn()
      return
    }
    // 战新产业筛选
    if (item.type === 'strategic_industry') {
      item.column = 'strategic_ind_list'
      item.config.column = 'strategic_ind_list'
      handleImmobilizationColumn()
      return
    }
    // 资质筛选
    if (item.type === 'qualification') {
      item.column = 'qualified_list'
      item.config.column = 'qualified_list'
      handleImmobilizationColumn()
      return
    }
    if (value === 'polymerize') {
      item.checkList = []
    } else if (value === 'pca') {
      Reflect.deleteProperty(item, 'column')
      item.config.province_column = ''
      item.config.city_column = ''
      item.config.area_column = ''
    }
    form.setFieldValue('settingList', settingList)
  }

  const handleChange = async (settingList: any, key: number, params: any) => {
    setloading(true)
    const { updateType } = settingList[key]
    Reflect.deleteProperty(params, 'checkList')
    Reflect.deleteProperty(params, 'columnCoreFieldRef')
    Reflect.deleteProperty(params, 'cityCoreFieldRef')
    Reflect.deleteProperty(params, 'areaCoreFieldRef')
    Reflect.deleteProperty(params, 'updateType')
    if (updateType === 'add') {
      return addDataItemSetting(params)
        .then((res) => {
          message.success('保存成功')
          callList()
          return !!res
        })
        .finally(() => {
          setloading(false)
        })
        .catch((error) => {
          callList()
          return Promise.reject(error)
        })
    } else {
      editDataItemSetting(params)
        .then((res) => {
          if (res) {
            message.success('保存成功')
            return callList()
          }
        })
        .finally(() => {
          setloading(false)
        })
        .catch((error) => {
          callList()
          return Promise.reject(error)
        })
    }
  }
  // 筛选字段
  const columnChange = async (key: number, value: string, option: { comment: any }) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    if (!item.type) {
      message.warning('请先选择筛选项类型')
      item.config.column = ''
      item.config.province_column = ''
      form.setFieldValue('settingList', settingList)
      return
    }
    if (item.type === 'pca') {
      if (item.config.city_column === value) {
        message.warning('市级已选过此字段')
        item.config.province_column = item.config.old_province_column || ''
        form.setFieldValue('settingList', settingList)
        return
      }
      if (item.config.area_column === value) {
        message.warning('区县级已选过此字段')
        item.config.province_column = item.config.old_province_column || ''
        form.setFieldValue('settingList', settingList)
        return
      }
    }
    item.name ||= option.comment
    // 新增
    if (item.updateType === 'add') {
      let params: any = { release_item_id: id, ...item, config: { column: value } }
      if (item.type === 'polymerize') {
        params.config.options = []
        item.column = value
        item.config.column = value
        item.polymerizeOptionsLength = 0
        item.checkList = []
        form.setFieldValue('settingList', settingList)
        return true
      }
      if (item.type === 'pca') {
        params = {
          release_item_id: id,
          ...item,
          config: {
            province_column: value,
            city_column: '',
            area_column: ''
          }
        }
      }
      const flag = await handleChange(settingList, key, params)
      if (!flag) {
        if (item.type === 'pca') {
          item.config.province_column = item.config.old_province_column || ''
        } else {
          item.config.column = item.config.old_column || ''
        }
        return
      }
      return flag
    } else {
      let params = { release_item_id: id, ...item, config: { column: value } }
      if (item.type === 'polymerize') {
        params.config.options = []
        item.column = value
        item.config.column = value
        item.polymerizeOptionsLength = 0
        item.checkList = []
        form.setFieldValue('settingList', settingList)
        return true
      }
      if (item.type === 'pca') {
        params = {
          release_item_id: id,
          ...item,
          config: {
            ...item.config,
            province_column: value
          }
        }
      }
      return handleChange(settingList, key, params)
    }
  }

  const updateColumnField = (key: number) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    if (item.disabled) {
      return
    }
    if (!item.type) {
      message.warning('请先选筛选项类型')
      return
    }
    settingList[key]?.columnCoreFieldRef?.showModal(id, item?.type === 'pca' ? item.config.province_column : item.config.column)
  }
  const updateCityField = (key: number) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    if (!item.config.province_column) {
      message.warning('请先选上级')
      return
    }
    settingList[key]?.cityCoreFieldRef?.showModal(id, item.config.city_column)
  }
  const updateAreaField = (key: number) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    if (!item.config.province_column) {
      message.warning('请先选上级')
      return
    }
    if (!item.config.city_column) {
      message.warning('请先选上级')
      return
    }
    settingList[key]?.areaCoreFieldRef?.showModal(id, item.config.area_column)
  }
  const checkPolymierize = (originSettingList: any[], key: number, checkList: string[]) => {
    const item = originSettingList[key]
    item.polymerizeOptionsLength = checkList.length
    if (item.polymerizeOptionsLength > 501) {
      form.setFieldValue('settingList', originSettingList)
      return
    }
    const params = { release_item_id: id, ...item, config: { ...item.config, options: checkList } }
    return handleChange(originSettingList, key, params)
  }
  // 市级
  const cityChange = (key: number, value: string) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    if (item.province_column === value) {
      message.warning('省级已选过此字段')
      item.config.city_column = item.config.old_city_column || ''
      form.setFieldValue('settingList', settingList)
      return
    }
    if (item.config.area_column === value) {
      message.warning('区县级已选过此字段')
      item.config.city_column = item.config.old_city_column || ''
      form.setFieldValue('settingList', settingList)
      return
    }
    if (item.updateType === 'add') {
      const params = {
        release_item_id: id,
        ...item,
        config: {
          ...item.config,
          city_column: value || ''
        }
      }
      const flag = handleChange(settingList, key, params)
      return flag
    } else {
      const params = {
        release_item_id: id,
        ...item,
        config: {
          ...item.config,
          city_column: value || ''
        }
      }
      return handleChange(settingList, key, params)
    }
  }
  // 区县级
  const districtChange = (key: number, value: string) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    if (item.province_column === value) {
      message.warning('省级已选过此字段')
      item.config.area_column = item.config.old_area_column || ''
      form.setFieldValue('settingList', settingList)
      return
    }
    if (item.config.city_column === value) {
      message.warning('市级已选过此字段')
      item.config.area_column = item.config.old_area_column || ''
      form.setFieldValue('settingList', settingList)
      return
    }
    if (item.updateType === 'add') {
      const params = {
        release_item_id: id,
        ...item,
        config: {
          ...item.config,
          area_column: value || ''
        }
      }
      const flag = handleChange(settingList, key, params)
      return flag
    } else {
      const params = {
        release_item_id: id,
        ...item,
        config: {
          ...item.config,
          area_column: value || ''
        }
      }
      return handleChange(settingList, key, params)
    }
  }
  // 筛选项名称
  const nameChange = (key: number, value: string) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    if (!item.type) {
      message.warning('请先选择筛选项类型')
      return
    }
    const params = { release_item_id: id, ...item, name: value }
    handleChange(settingList, key, params)
  }
  const showSelectedColumnText = (key: number) => {
    let text = ''
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    if (item.type === 'pca') {
      text = item.province_column
    } else {
      text = item.column
    }
    if (!text) {
      text = '请选择筛选字段'
    }
    return text
  }
  // 筛选字段
  const showColumnFieldButton = (key: number) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    const style = {
      color: (item.column || item.province_column) && !item.disabled ? 'rgba(0, 0, 0, 0.88)' : 'rgba(0, 0, 0, 0.25)',
      cursor: item.disabled ? 'not-allowed' : 'pointer',
      background: item.disabled ? 'rgba(0, 0, 0, 0.04)' : '#fff'
    }

    return (
      <Button className="w-full" onClick={() => updateColumnField(key)} style={style}>
        {showSelectedColumnText(key)}
      </Button>
    )
  }
  const showPolymerizeOptionsChecked = (key: number) => {
    const settingList = form.getFieldValue('settingList')
    const item = settingList[key]
    if (item.polymerizeOptionsLength <= 500) {
      if (item.checkList?.length) {
        return `已选${item.checkList.length}/${item.polymerizeOptionsLength}`
      } else {
        return '待配置'
      }
    } else {
      return '无效字段'
    }
  }

  useEffect(() => {
    reqDataItemColumns({
      id
    }).then((res) => {
      allColumnList.current = res
      settypeInfor((prev: { columnList: any }) => {
        prev.columnList = res
      })
    })
  }, [])

  useEffect(() => {
    const { columnList, tableList } = typeInfor
    // 园区筛选
    const hasParkItem = columnList.find((item: { name: string }) => item.name === 'carrier_list')
    const listHasPark = tableList.find((item: { type: string }) => item.type === 'park')
    setTypeOptions((prev: any[]) => {
      const _index = prev.findIndex((item) => item.value === 'park')
      if (!hasParkItem || listHasPark) {
        prev[_index].disabled = true
      } else {
        prev[_index].disabled = false
      }
      return [...prev]
    })

    // 产业筛选
    const hasIndustryItem = columnList.find((item: { name: string }) => item.name === 'hs_ind_list')
    const listHasIndustry = tableList.find((item: { type: string }) => item.type === 'industry')
    setTypeOptions((prev: any[]) => {
      const _index = prev.findIndex((item) => item.value === 'industry')
      if (!hasIndustryItem || listHasIndustry) {
        prev[_index].disabled = true
      } else {
        prev[_index].disabled = false
      }
      return [...prev]
    })

    // 国民经济分类筛选
    const hasNationalEconomyItem = columnList.find((item: { name: string }) => item.name === 'nea_ind_list')
    const listHasNationalEconomy = tableList.find((item: { type: string }) => item.type === 'national_economy_classification')
    setTypeOptions((prev: any[]) => {
      const _index = prev.findIndex((item) => item.value === 'national_economy_classification')
      if (!hasNationalEconomyItem || listHasNationalEconomy) {
        prev[_index].disabled = true
      } else {
        prev[_index].disabled = false
      }
      return [...prev]
    })

    // 战新产业筛选
    const hasWarNewIndustryItem = columnList.find((item: { name: string }) => item.name === 'strategic_ind_list')
    const listHasStrategicIndustry = tableList.find((item: { type: string }) => item.type === 'strategic_industry')
    setTypeOptions((prev: any[]) => {
      const _index = prev.findIndex((item) => item.value === 'strategic_industry')
      if (!hasWarNewIndustryItem || listHasStrategicIndustry) {
        prev[_index].disabled = true
      } else {
        prev[_index].disabled = false
      }
      return [...prev]
    })

    // 资质筛选
    const hasQualificationItem = columnList.find((item: { name: string }) => item.name === 'qualified_list')
    const listHasQualification = tableList.find((item: { type: string }) => item.type === 'qualification')
    setTypeOptions((prev: any[]) => {
      const _index = prev.findIndex((item) => item.value === 'qualification')
      if (!hasQualificationItem || listHasQualification) {
        prev[_index].disabled = true
      } else {
        prev[_index].disabled = false
      }
      return [...prev]
    })
  }, [typeInfor])

  return (
    <>
      {loading && <HsAdminSpin />}
      <Form form={form}>
        <Form.List name="settingList">
          {(fields, { add }) => (
            <>
              {!!fields?.length && (
                <Row gutter={16}>
                  <Col span={5}>
                    <Flex>筛选项类型</Flex>
                  </Col>
                  <Col span={5}>
                    <Flex align="center" gap={'small'}>
                      <b style={{ color: 'red' }}>*</b>筛选字段
                    </Flex>
                  </Col>
                </Row>
              )}
              {fields.map(({ key, name, ...restField }) => (
                <Row key={key} gutter={16} className="mt-2">
                  <Col span={5}>
                    <Flex gap={'small'}>
                      <HsAdminDelete
                        onConfirm={() => {
                          const settingList = form.getFieldValue('settingList')
                          const item = settingList[key]
                          if (item.id) {
                            deleteDataItemSetting({ release_item_id: id, id: item.id }).then(() => {
                              message.success('删除成功')
                              callList()
                            })
                          } else {
                            settingList.splice(key, 1)
                            form.setFieldValue('settingList', settingList)
                          }
                        }}
                        className="mb-6"
                      />
                      {/* 筛选项类型 */}
                      <Form.Item {...restField} name={[name, 'type']} rules={[{ required: true, message: '请选择筛选项类型' }]} className="w-full">
                        <HsAdminSelect
                          options={typeOptions}
                          placeholder="请选择筛选项类型"
                          onChange={(value: string) => typeChange(key, value)}
                          allowClear={false}
                          disabled={form.getFieldValue('settingList')[key]?.updateType === 'edit' ? true : false}
                        />
                      </Form.Item>
                    </Flex>
                  </Col>
                  <Col span={4}>
                    {/* 筛选字段 */}
                    <Form.Item
                      label={form.getFieldValue('settingList')[key]?.type === 'pca' ? '省级' : ''}
                      {...restField}
                      name={[name, 'config', form.getFieldValue('settingList')[key]?.type === 'pca' ? 'province_column' : 'column']}
                      rules={[{ required: true, message: '请选择筛选字段' }]}>
                      {showColumnFieldButton(key)}
                    </Form.Item>
                    <ServerCoreField
                      ref={(el) => {
                        const settingList = form.getFieldValue('settingList')
                        const item = settingList[key]
                        if (item) {
                          item.columnCoreFieldRef = el
                        }
                      }}
                      onSelectChange={(value: string, option: { comment: any }) => columnChange(key, value, option)}
                    />
                  </Col>

                  <Col span={4}>
                    {/* 聚合 */}
                    {form.getFieldValue('settingList')[key]?.type === 'polymerize' && form.getFieldValue('settingList')[key]?.column && (
                      <Form.Item label="选择筛选项" {...restField} name={[name, 'polymerize_filters']}>
                        <Button
                          type="link"
                          onClick={() => {
                            polymerizeOptionsRef.current.showModal(
                              id,
                              form.getFieldValue('settingList'),
                              key,
                              form.getFieldValue('settingList')[key].checkList
                            )
                          }}>
                          {showPolymerizeOptionsChecked(key)}
                        </Button>
                      </Form.Item>
                    )}
                    {/* 市级 */}
                    {form.getFieldValue('settingList')[key]?.type === 'pca' && (
                      <>
                        <Form.Item label="市级" {...restField} name={[name, 'city_column']}>
                          <Button
                            className="w-full"
                            onClick={() => updateCityField(key)}
                            style={{
                              color: form.getFieldValue('settingList')[key].city_column ? 'rgba(0, 0, 0, 0.88)' : 'rgba(0, 0, 0, 0.25)'
                            }}>
                            {form.getFieldValue('settingList')[key].city_column || '请选择市级'}
                          </Button>
                        </Form.Item>
                        <ServerCoreField
                          ref={(el) => {
                            const settingList = form.getFieldValue('settingList')
                            const item = settingList[key]
                            if (item) {
                              item.cityCoreFieldRef = el
                            }
                          }}
                          onSelectChange={(value: string) => cityChange(key, value)}
                        />
                      </>
                    )}
                  </Col>
                  <Col span={4}>
                    {form.getFieldValue('settingList')[key]?.type === 'pca' && (
                      <>
                        <Form.Item label="区县级" {...restField} name={[name, 'area_column']}>
                          <Button
                            className="w-full"
                            onClick={() => updateAreaField(key)}
                            style={{
                              color: form.getFieldValue('settingList')[key].area_column ? 'rgba(0, 0, 0, 0.88)' : 'rgba(0, 0, 0, 0.25)'
                            }}>
                            {form.getFieldValue('settingList')[key].area_column || '请选择区县级'}
                          </Button>
                        </Form.Item>
                        <ServerCoreField
                          ref={(el) => {
                            const settingList = form.getFieldValue('settingList')
                            const item = settingList[key]
                            if (item) {
                              item.areaCoreFieldRef = el
                            }
                          }}
                          onSelectChange={(value: string) => districtChange(key, value)}
                        />
                      </>
                    )}
                  </Col>

                  <Col span={7}>
                    <Form.Item label="筛选项名称" {...restField} name={[name, 'name']}>
                      <HsAdminInput
                        placeholder="请输入筛选项名称"
                        onPressEnter={(e: { target: { value: string } }) => nameChange(key, e.target.value)}
                        onBlur={(e: { target: { value: string } }) => nameChange(key, e.target.value)}
                      />
                    </Form.Item>
                  </Col>
                </Row>
              ))}
              <Form.Item>
                <Button
                  type="primary"
                  onClick={() => {
                    const settingList = form.getFieldValue('settingList')
                    if (settingList.length && !settingList.at(-1).type) {
                      message.warning('只能有一条空白数据，请先将空白数据填写完再添加')
                      return
                    }
                    add({ type: null, updateType: 'add', column: '', name: '', config: { column: '' } })
                  }}>
                  + 增加筛选项
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </Form>
      <Flex justify="end">
        <HsAdminPage {...pagination} />
      </Flex>
      <PolymerizeOptions ref={polymerizeOptionsRef} onCheckPolymierize={checkPolymierize} />
    </>
  )
}

export default memo(Filtrate)
